//日志
const {
    logger
} = require('../config/logger');

//引入数据库连接池
const pool = require('../config/mysql');
//引入数据库语句
const noticeQuery = require('../db/noticeQuery/noticeQuery');

//引入时间模块
const sd = require('silly-datetime');

//引入accessToken生成
const accessToken = require('../utils/getAccessToken');

//引入发送订阅信息
const {
    sendSubscribeMsg_auth,
    sendSubscribeMsg_note,
    sendSubscribeMsg_visitor,
    sendSubscribeMsg_visitor_admin,
    sendSubscribeMsg_owner_admin,
    sendSubscribeMsg_visitor_house
} = require("../utils/sendSubscribeMsg");

let _io = null,
    _hashName = new Map();

//初始化全局变量
function auditNotice(io, hashName) {
    _io = io;
    _hashName = hashName;
}

//发送系统通知租客认证消息
function sendSystemMessage_auth(userId, mess) {
    if (_hashName.has(userId)) {
        const toSocket = _hashName.get(userId);
        _io.to(toSocket).emit('system_message', JSON.stringify({
            mess: "用户在线，实时信息",
            applicant: mess.applicant,
            message: mess.message,
            time: mess.time,
            tenantId: mess.tenantId
        }));
    } else {
        const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        pool.query(noticeQuery.insert_notive, [userId, mess.tenantId, "认证审核信息", mess.message, time], (error, result) => {
            if (error) {
                logger().error("认证审核信息失败: " + error);
                return;
            } else {
                //获取accessToken
                accessToken.getAccessToken().then(res => {
                    const ast = res;
                    //执行发送订阅认证信息
                    sendSubscribeMsg_auth(ast, mess.openId, mess.applicant, mess.time)
                        .then(res => {
                            logger().info("发送订阅信息成功: " + res);
                        }).catch(err => {
                            logger().error("认证审核信息失败: " + err);
                        })
                }).catch(err => {
                    logger().error("认证审核信息失败: " + err);
                })
            }
        });
    }
}

//发送系统通知小纸条消息
function sendSystemMessage_note(userId, mess) {
    if (_hashName.has(userId)) {
        const toSocket = _hashName.get(userId);
        _io.to(toSocket).emit('system_message', JSON.stringify({
            mess: "用户在线，实时信息",
            sender: mess.sender,
            message: mess.message,
            time: mess.time,
            noteId: mess.noteId
        }));
    } else {
        const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        pool.query(noticeQuery.insert_notive, [userId, mess.noteId, "小纸条信息", mess.message, time], (error, result) => {
            if (error) {
                logger().error("发送小纸条订阅信息失败: " + error);
                return;
            } else {
                //获取accessToken
                accessToken.getAccessToken().then(res => {
                    const ast = res;
                    //执行发送订阅信息
                    sendSubscribeMsg_note(ast, mess.openId, mess.sender, mess.content, mess.time)
                        .then(res => {
                            logger().info("发送小纸条订阅信息成功: " + res);
                        }).catch(err => {
                            logger().error("发送小纸条订阅信息失败: " + err);
                        })
                }).catch(err => {
                    logger().error("发送小纸条订阅信息失败: " + err);
                })
            }
        });
    }
}

//发送系统通知访客申请消息
function sendSystemMessage_visitor(userId, mess) {
    if (_hashName.has(userId)) {
        const toSocket = _hashName.get(userId);
        _io.to(toSocket).emit('system_message', JSON.stringify({
            mess: "用户在线，实时信息",
            message: mess.message,
            time: mess.time,
            visitorId: mess.visitorId
        }));
    } else {
        const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        pool.query(noticeQuery.insert_notive, [userId, mess.visitorId, "访客申请信息", mess.message, time], (error, result) => {
            if (error) {
                logger().error("发送访客申请信息订阅信息失败: " + error);
                return;
            } else {
                //获取accessToken
                accessToken.getAccessToken().then(res => {
                    const ast = res;
                    //执行发送订阅信息
                    sendSubscribeMsg_visitor(ast, mess.openId, mess.applicant, mess.time)
                        .then(res => {
                            logger().info("发送访客申请信息订阅信息成功: " + res);
                        }).catch(err => {
                            logger().error("发送访客申请信息订阅信息失败: " + err);
                        })
                }).catch(err => {
                    logger().error("发送访客申请信息订阅信息失败: " + err);
                })
            }
        });
    }
}

//发送系统通知访客>业主处理申请消息
function sendSystemMessage_visitor_houseHold(userId, mess) {
    mess.visitorStatus == "0" ? mess.visitorStatus = "不同意" : "同意";
    if (_hashName.has(userId)) {
        const toSocket = _hashName.get(userId);
        _io.to(toSocket).emit('system_message', JSON.stringify({
            mess: "用户在线，实时信息",
            message: mess.message,
            status: mess.visitorStatus,
            time: mess.time,
            visitorId: mess.visitorId
        }));
    } else {
        const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        pool.query(noticeQuery.insert_notive, [userId, mess.visitorId, "访客申请已受业主处理", mess.message, time], (error, result) => {
            if (error) {
                logger().error("通知访客业主审核订阅信息失败: " + error);
                return;
            } else {
                //获取accessToken
                accessToken.getAccessToken().then(res => {
                    const ast = res;
                    if (mess.time)
                        //执行发送订阅信息
                        sendSubscribeMsg_visitor_house(ast, mess.openId, mess.handler, mess.visitorStatus, mess.time)
                        .then(res => {
                            logger().error("通知访客业主审核订阅信息成功: " + res);
                        }).catch(err => {
                            logger().error("通知访客业主审核订阅信息失败: " + err);
                        })
                }).catch(err => {
                    logger().error("通知访客业主审核订阅信息失败: " + err);
                })
            }
        });
    }
}

//发送系统通知访客>管理员处理申请消息
function sendSystemMessage_visitor_admin(userId, mess) {
    if (_hashName.has(userId)) {
        const toSocket = _hashName.get(userId);
        _io.to(toSocket).emit('system_message', JSON.stringify({
            mess: "用户在线，实时信息",
            message: mess.message,
            time: mess.time,
            visitorId: mess.visitorId
        }));
    } else {
        const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        pool.query(noticeQuery.insert_notive, [userId, mess.visitorId, "访客申请信息", mess.message, time], (error, result) => {
            if (error) {
                logger().error("访客管理员审核订阅信息失败: " + error);
                return;
            } else {
                //获取accessToken
                accessToken.getAccessToken().then(res => {
                    const ast = res;
                    //执行发送订阅信息
                    sendSubscribeMsg_visitor_admin(ast, mess.openid, mess.handler, mess.time)
                        .then(res => {
                            logger().info("访客管理员审核订阅信息成功: " + err);
                        }).catch(err => {
                            logger().error("访客管理员审核订阅信息失败: " + err);
                        })
                }).catch(err => {
                    logger().error("访客管理员审核订阅信息失败: " + err);
                })
            }
        });
    }
}

//发送系统通知业主>管理员处理申请消息（业主认证订阅消息）
function sendSystemMessage_owner_admin(userId, mess) {
    if (_hashName.has(userId)) {
        const toSocket = _hashName.get(userId);
        _io.to(toSocket).emit('system_message', JSON.stringify({
            mess: "用户在线，实时信息",
            message: mess.message,
            time: mess.time,
            ownerId: mess.ownerId
        }));
    } else {
        const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        pool.query(noticeQuery.insert_notive, [userId, mess.ownerId, "业主审核信息", mess.message, time], (error, result) => {
            if (error) {
                logger().error("通知业主管理员审核订阅信息失败: " + error);
                return;
            } else {
                //获取accessToken
                accessToken.getAccessToken().then(res => {
                    const ast = res;
                    //执行发送订阅信息
                    sendSubscribeMsg_owner_admin(ast, mess.openid, mess.handler, mess.time)
                        .then(res => {
                            logger().info("通知业主管理员审核订阅信息成功: " + res);
                        }).catch(err => {
                            logger().error("通知业主管理员审核订阅信息失败: " + err);
                        })
                }).catch(err => {
                    logger().error("通知业主管理员审核订阅信息失败: " + err);
                })
            }
        });
    }
}
module.exports = {
    auditNotice,
    sendSystemMessage_auth,
    sendSystemMessage_note,
    sendSystemMessage_visitor,
    sendSystemMessage_visitor_houseHold,
    sendSystemMessage_visitor_admin,
    sendSystemMessage_owner_admin
};